package com.example.blackmarket;

/**
 * Created by ThinkPad on 2020/10/17.
 */

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;

import java.util.List;

/**
 * Created by ThinkPad on 2020/10/14.
 */

public class HomeSortAdapter extends RecyclerView.Adapter<HomeSortAdapter.ViewHolder>{
    private List<HomeSort> mHomeSortList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        View HomeSortView;
        ImageView HomeSortImage;
        TextView HomeSortName;

        //构造函数
        //要传入View参数，通常就是RecyclerView子项的最外层布局
        public ViewHolder(View view){
            super(view);
            HomeSortView=view;
            HomeSortImage=(ImageView)view.findViewById(R.id.home_sort_image);
            HomeSortName=(TextView)view.findViewById(R.id.home_sort_name);
        }
    }

    public HomeSortAdapter(List<HomeSort> homesortList){
        mHomeSortList=homesortList;
    }

    //用于创建ViewHolder实例
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.home_sort_item,parent,false);
        final ViewHolder holder=new ViewHolder(view);

        //首页分类图标的点击事件
        holder.HomeSortView.setOnClickListener((new View.OnClickListener(){
            @Override
            public void onClick(View v){
                int position=holder.getAdapterPosition();
                HomeSort homesort=mHomeSortList.get(position);
                Toast.makeText(v.getContext(),"you clicked on "+homesort.getName(),Toast.LENGTH_SHORT).show();
            }
        }));
        return holder;
    }

    //对RecyclerView子项数据进行赋值，会在每个子项被滚动到屏幕内时被执行
    //通过position得到当前项的Fruit实例，然后再将数据设置到ViewHolder的ImageView和TextView中
    @Override
    public void onBindViewHolder(ViewHolder holder,int position){
        HomeSort homesort=mHomeSortList.get(position);
        holder.HomeSortImage.setImageResource(homesort.getImageId());
        holder.HomeSortName.setText(homesort.getName());
    }

    @Override
    public int getItemCount(){
        return mHomeSortList.size();
    }
}
